package com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.service;

import com.yonyou.ucf.mdf.app.isvdxq.ReturnResult.DataResult;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.entity.LocationQdEntity;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.mapper.LocationMapperImpl;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.LocationTreeBean;
import com.yonyou.ucf.mdf.app.isvdxq.firstpart.location.model.LocationViewModel;
import com.yonyou.ucf.mdf.app.isvdxq.utils.MyTool;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class LocationEntityService {

    @Autowired
    LocationMapperImpl locationMapper;

    public LocationEntity getLocationById(String locationId, String tenantId) {
        return locationMapper.getLocationById(locationId, tenantId);
    }

    public List<LocationEntity> getLocationByIds(List<String> strList, String tenantId) {
        return locationMapper.selectLocationByIds(strList, tenantId);
    }

    public List<LocationEntity> GetLocationByWarehouseId(String warehouseId, String tenantId) {
        return locationMapper.getLocationByWId(warehouseId, tenantId);
    }

    public List<LocationEntity> getLocationByWhIds(List<String> ids, String tenantId) {
        return locationMapper.getLocationByWhIds(ids, tenantId);
    }

    //新增并更新
    public Integer InsertBatch(List<LocationEntity> list) {
        if (list.size() == 0) return 0;
        long start = System.currentTimeMillis();
        int res = locationMapper.insertBatch(list);
        long end = System.currentTimeMillis();
        System.out.println("---------------" + (start - end) + "---------------");
        return res;
    }

    public List<LocationEntity> getLocationEntityAll(String tenantId, String warehouse_id, String level, String locationCode) throws Exception {
        return locationMapper.getLocationEntityAll(tenantId, warehouse_id, level, locationCode);
    }

    public List<LocationQdEntity> getLocationQdEntityAll(String tenantId, String warehouse_id, String level, String locationCode) throws Exception {
        return locationMapper.getLocationQdEntityAll(tenantId, warehouse_id, level, locationCode);
    }

    public int GetLocationNumByParentId(String locationId, String tenantId) {
        int rInt = locationMapper.GetLocationNumByParentId(locationId, tenantId);
        return rInt;
    }

    /**
     * 递归获取子集Id
     *
     * @param locationId locationId
     * @return 返回一个子集合数组
     */
    public List<String> GetLocationIDs(String locationId, String tenantid) {
        List<String> resList = new ArrayList<>();
        List<LocationEntity> locationList = locationMapper.GetLocationByParentId(locationId, tenantid);
        if (locationList.size() > 0) {
            for (LocationEntity item : locationList) {
                resList.addAll(GetLocationIDs(item.getId(), tenantid));
            }
        } else resList.add(locationId);
        return resList;
    }

    /**
     * 获取返回一个父级集合
     *
     * @param locationId locationId
     * @return 返回一个父级集合
     */
    public List<String> GetLocationIDParents(String locationId, List<String> resList, String tenantId) {
        LocationEntity locationEntity = locationMapper.getLocationById(locationId, tenantId);
        if (locationEntity == null) return resList;
        if (StringUtils.isEmpty(locationEntity.getPath())) {
            resList.add(locationEntity.getWarehouse_id());
        } else {
            List<String> pathIds = Arrays.asList(locationEntity.getPath().split("\\|"));
            resList.addAll(pathIds);
        }
        return resList;
    }

    /**
     * 递归获取 货位全路径
     *
     * @param locationId
     * @param resList
     * @param tenantId
     * @return
     */
    public List<String> GetLocationFullName(String locationId, List<String> resList, String tenantId) {
        LocationEntity locationEntity = locationMapper.getLocationById(locationId, tenantId);
        if (locationEntity == null) return resList;
        if (!StringUtils.isEmpty(locationEntity.getParent_id())) {
            resList.add(locationEntity.getLocationName());
            return GetLocationFullName(locationEntity.getParent_id(), resList, tenantId);
        } else {
            return resList;
        }
    }

    public static String GetLocationFullNameEx(String locationId, List<LocationEntity> dataList, String locationName) {
        LocationEntity locationEntity = dataList.stream().filter(u -> u.getId().equals(locationId)).findAny().orElse(null);
        if (locationEntity != null) {
            locationName = locationEntity.getLocationName() + locationName;
            String parentId = locationEntity.getParent_id();
            if (!StringUtils.isEmpty(parentId)) {
                return GetLocationFullNameEx(parentId, dataList, locationName);
            }
        }
        return locationName;
    }

    /**
     * 货位树结构查询支持组织过滤
     *
     * @param locationId
     * @param orgid
     * @return
     */
    public List<LocationTreeBean> GetLocationTree(String locationId, List<String> orgid, String tenantId) {
        List<LocationEntity> myList = new ArrayList<>();
        List<LocationTreeBean> resList = new ArrayList<>();
        if (StringUtils.isEmpty(locationId)) {
            List<LocationEntity> locationList = new ArrayList<>();
            if (orgid.size() == 0) locationList = locationMapper.GetLocationAll(tenantId, "0");
            else locationList = locationMapper.GetLocationAllByOrg(tenantId, "0", orgid);
            myList = MyTool.convertBeanList(locationList, LocationEntity.class);
        } else {
            List<LocationEntity> locationList = new ArrayList<>();
            if (orgid.size() == 0) locationList = locationMapper.GetLocationChildren(locationId);
            else locationList = locationMapper.GetLocationChildrenByOrg(locationId, orgid);
            myList = MyTool.convertBeanList(locationList, LocationEntity.class);
        }
        if (myList.size() > 0) {
            resList = MyTool.convertBeanList(myList, LocationTreeBean.class);
            for (LocationTreeBean item : resList) {
                item.setParent(item.getParent_id());
                item.setParentName(item.getParent_name());
                item.setWarehouseCode(item.getWarehouse_code());
                item.setWarehouseID(item.getWarehouse_id());
                item.setWarehouseName(item.getWarehouse_name());
                if (GetLocationNumByParentId(item.getId(), tenantId) > 0) {
                    item.setChildren(GetLocationTree(item.getId(), orgid, tenantId));
                }
            }
        }
        return resList;
    }


    // 根据locationId获取其子集内容
    public List<LocationViewModel> GetList(String parentId, String level, String tenantid, String locationCode) {
        List<LocationViewModel> locationList = new ArrayList<>();
        if (StringUtils.isEmpty(level)) {
            level = "0";
        }
        List<LocationEntity> locationEntities = locationMapper.GetListEx(parentId, level, tenantid, locationCode);
        if (locationEntities.size() > 0) {
            List<LocationEntity> allLocationList = GetLocationByWarehouseId(locationEntities.get(0).getWarehouse_id(), tenantid);
            for (LocationEntity item : locationEntities) {
                LocationViewModel locationViewModel = MyTool.convertBean2Bean(item, LocationViewModel.class);
                String pathName = LocationEntityService.GetLocationFullNameEx(item.getId(), allLocationList, "");
                locationViewModel.setPathName(pathName);
                locationViewModel.setIsEnd(String.valueOf(item.getIsEnd()));
                locationList.add(locationViewModel);
            }
        }

        return locationList;
    }
    public List<LocationViewModel> GetListEx(String parentId, String level, String tenantid, String locationCode) {
        List<LocationViewModel> locationList = new ArrayList<>();
        List<LocationEntity> locationEntities = locationMapper.GetListEx(parentId, level, tenantid, locationCode);
        if (locationEntities.size() > 0) {
            List<LocationEntity> allLocationList = GetLocationByWarehouseId(locationEntities.get(0).getWarehouse_id(), tenantid);
            for (LocationEntity item : locationEntities) {
                LocationViewModel locationViewModel = MyTool.convertBean2Bean(item, LocationViewModel.class);
                String pathName = LocationEntityService.GetLocationFullNameEx(item.getId(), allLocationList, "");
                locationViewModel.setPathName(pathName);
                locationViewModel.setIsEnd(String.valueOf(item.getIsEnd()));
                locationList.add(locationViewModel);
            }
        }

        return locationList;
    }

    /**
     * 获取货架主键 0仓库|1区域|2货架|
     * 强制level层级结构
     *
     * @param locationID
     * @param tenantId
     * @return
     */
    public String GetHuojiaID(String locationID, String tenantId) {
        String result = "";
        LocationEntity entity = locationMapper.getLocationById(locationID, tenantId);
        if (entity == null || entity.getLevel() == 0) return result;
        String path = entity.getPath().replace(String.format("%s|", entity.getWarehouse_id()), "");
        path = String.format("%s|", entity.getWarehouse_id()) + path;
        String[] arr_Ids = path.split("\\|");
        if (arr_Ids.length < 3) return result;
        result = arr_Ids[2];

        return result;
    }

    /**
     * 获取货架主键 0仓库|1区域|2货架|
     * path 分隔
     * @param entity
     * @param tenantId
     * @return
     */
    public static String GetHuojiaIDByEntity(LocationEntity entity, String tenantId) {
        String result = "";
        if (entity == null || entity.getLevel() == 0) return result;
        if (StringUtils.isEmpty(entity.getPath()) || StringUtils.isEmpty(entity.getWarehouse_id())) return result;
        String path = entity.getPath().replace(String.format("%s|", entity.getWarehouse_id()), "");
        path = String.format("%s|", entity.getWarehouse_id()) + path;
        String[] arr_Ids = path.split("\\|");
        if (arr_Ids.length < 3) return result;
        result = arr_Ids[2];

        return result;
    }

    /**
     * 根据Rfid获取仓库信息
     *
     * @param epccode
     * @param tenantId
     * @param warehouseList
     * @return
     */
    public DataResult selectLocationByEpc(String epccode, String tenantId, List<String> warehouseList) {
        DataResult result = new DataResult(0, "出现异常");

        List<LocationEntity> lastLocation = locationMapper.getLocationByEpc(epccode, tenantId);
        if (lastLocation.size() == 0) {
            result.setMessage("该标签无货位信息");
            return result;
        } else if (lastLocation.size() > 1) {
            result.setMessage("标签存在异常，可能重复绑定。");
            return result;
        }
        if (warehouseList != null && warehouseList.size() > 0) {
            List<LocationEntity> collect = lastLocation.stream().filter(it -> warehouseList.contains(it.getWarehouse_id())).collect(Collectors.toList());
            if (collect.size() != 1) {
                result.setStatus(2);
                result.setMessage("当前货位的库存组织与当前用户的库存组织不一致！");
                return result;
            }
        }
        LocationViewModel locationViewModel = MyTool.convertBean2Bean(lastLocation.get(0), LocationViewModel.class);
        List<LocationEntity> allLocationList = GetLocationByWarehouseId(lastLocation.get(0).getWarehouse_id(), tenantId);
        String pathName = LocationEntityService.GetLocationFullNameEx(lastLocation.get(0).getId(), allLocationList, "");
        locationViewModel.setPathName(pathName);
        locationViewModel.setIsEnd(String.valueOf(lastLocation.get(0).getIsEnd()));
        result.setStatus(1);
        result.setMessage("找到对应货位信息");
        result.setData(locationViewModel);

        return result;
    }

    /**
     * 自定义更新实体
     *
     * @param key
     * @param val
     * @param valnew
     * @return
     */
    public int updateLocation(String key, String val, String valnew, String tenantId) {
        return locationMapper.updateEntity(key, val, valnew, tenantId);
    }

    /**
     * 获取指定范围 货位Ids
     * @param key
     * @param tenantId
     * @return
     */
    public List<String> GetLocationIdsByPath(String key, String tenantId) {
        String locationID = "%" + key + "%";
        List<LocationEntity> tempList = locationMapper.GetLocationListByPath(locationID, tenantId);
        return tempList.stream().filter(it -> it.getIsEnd().equals(true)).map(it -> it.getId()).collect(Collectors.toList());
    }

    /**
     * 获取指定范围 货位
     * @param key
     * @param tenantId
     * @return
     */
    public List<LocationEntity> GetLocationListByPath(String key, String tenantId) {
        String locationID = "%" + key + "%";
        List<LocationEntity> tempList = locationMapper.GetLocationListByPath(locationID, tenantId);
        return tempList;
    }

    /**
     * 查询货位占用数量
     * @param locationId
     * @param tenantId
     * @return
     */
    public int GetEPCNumByLocationId(String locationId, String tenantId){
        return locationMapper.getEPCNumByLocationId(locationId, tenantId);
    }
    public int DeleteByPrimaryKey(String locationId, String tenantId){
        return locationMapper.deleteByPrimaryKey(locationId, tenantId);
    }
    public int UpdateLocationByWhCode(String warehousename, String warehousecode, String tenant_id){
        return locationMapper.updateLocationByWhCode(warehousename,warehousecode,tenant_id);
    }
    public int UpdateLocationPNameByIds(String warehousename, List<String> strList, String tenant_id){
        return locationMapper.updateLocationPNameByIds(warehousename,strList,tenant_id);
    }
    public int UpdateLocationByName(String warehousename, String locationId, String tenant_id) {
        return locationMapper.updateLocationByName(warehousename, locationId, tenant_id);
    }

    public List<LocationEntity> GetLocationByWarehouseCode(String warehouseCode, String tenantId) {
        return locationMapper.getLocationByWCode(warehouseCode, tenantId);
    }
    // 更新是否末级
    public int UpdateLocationForEnd(String tenantId, String id,int isEnd) {
        return locationMapper.updateLocationForEnd(isEnd, id, tenantId);
    }
    // 删除后检测
    public int UpdateLocationForEnd(String tenantId, String id) {
        int rInt = locationMapper.GetLocationNumByParentId(id, tenantId);
        if (rInt > 0) return rInt;
        //变更为末级
        return locationMapper.updateLocationForEnd(1, id, tenantId);
    }
}
